package com.harry.configuration.data_interchange;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.ArrayUtils;

import com.harry.configuration.ConstSettings;
import com.harry.utility.InnerUtils;

import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@NoArgsConstructor
public class RpcResult {

	private boolean result = false;

	private String message;

	private Map<String, Object> data;

	private StackTraceElement[] stacks;

	/**
	 * 响应网络请求的统一包装
	 * 
	 * @param e
	 */
	public RpcResult(Throwable e) {
		for (Set<Throwable> es = new HashSet<>(); e.getCause() != null && e.getCause().getMessage() != null
				&& es.add(e); e = e.getCause())
			;
		this.message = readStackMessage(e);
		if (skpiExps.contains(e)) {
		} else if (e.getStackTrace().length > 0) {
			this.stacks = ArrayUtils.subarray(e.getStackTrace(), 0, Math.min(10, e.getStackTrace().length));
		}
	}

	public RpcResult(Map<String, Object> data) {
		this(true, null, data);
	}

	public RpcResult(boolean result, String message, Map<String, Object> data) {
		this.result = result;
		this.message = message;
		this.data = data;
	}

	private String readStackMessage(Throwable e) {
		if (e != ConstSettings.oauthFailError) {
			InnerUtils.tryCatch(() -> {
				throw new Exception(e);
			});
		}
		String message = InnerUtils.ifNull(e.getMessage(),
				() -> (e.getStackTrace().length > 0 ? e.getStackTrace()[0].toString() : "No Stack Message"));
		int pindex = message.indexOf("(");
		if (pindex > 0) {
			message = message.substring(0, pindex);
		}
		return message;
	}

	private static Set<Throwable> skpiExps = new HashSet<>();
	static {
		skpiExps.add(ConstSettings.NO_PERMISSION);
		skpiExps.add(ConstSettings.oauthFailError);
		skpiExps.add(ConstSettings.userDisactived);
	}
}
